package net.sf.midollo.io.retry;

import net.sf.midollo.io.IOStream;
import net.sf.midollo.io.IOStreamFactory;

import java.io.IOException;

public class RetryManager {

	protected final IOStreamFactory ioStreamFactory;
	protected final int retries;
	protected final long delay;
	protected IOStream ioStream;

	public RetryManager(IOStreamFactory ioStreamFactory, int retries, long delay) {
		this.ioStreamFactory = ioStreamFactory;
		this.retries = retries;
		this.delay = delay;
	}

	public void write(byte[] b, int off, int len) throws IOException {
		int n = this.retries;
		while (true) {
			try {
				this.ioStream.getOutput().write(b, off, len);
				break;
			} catch (IOException e) {
				if (--n <= 0)
					throw e;
				try {
					Thread.sleep(this.delay);
				} catch (InterruptedException e1) {
					throw e;
				}
				reconnect();
			}
		}
	}

	public void flush() throws IOException {
	}

	public void close() throws IOException {
	}

	protected void connect() {
	}

	protected void reconnect() {
		try {
			this.ioStream.close();
		} catch (IOException e) {
		}
		try {
			this.ioStream = this.ioStreamFactory.open();
		} catch (IOException e) {
		}
	}
}
